<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>PayPal Apple Pay Demo</title>
    <script src="https://applepay.cdn-apple.com/jsapi/1.latest/apple-pay-sdk.js"></script>
    <script src="https://www.paypal.com/sdk/js?client-id=${clientId}&currency=${currency}&buyer-country=${buyerCountry}&merchant-id=${merchantId}&components=applepay"></script>
</head>
<body>
<h2>Pay with Apple Pay (via PayPal)</h2>
<div id="applepay-container"></div>

<script>
    (function(){
        // check for ApplePaySession support
        if (!window.ApplePaySession || !ApplePaySession.canMakePayments()) {
            console.warn("This device/browser does not support Apple Pay.");
            document.getElementById('applepay-container').innerText = "Apple Pay not supported on this device/browser.";
            return;
        }

        const applepay = paypal.Applepay();

        // fetch config and show button if eligible
        applepay.config()
            .then(cfg => {
                if (cfg.isEligible) {
                    document.getElementById("applepay-container").innerHTML =
                        '<apple-pay-button id="btn-appl" buttonstyle="black" type="buy" locale="en"></apple-pay-button>';
                    document.getElementById("btn-appl").addEventListener('click', onApplePayClicked);
                } else {
                    document.getElementById('applepay-container').innerText = "Apple Pay not eligible for this user/device.";
                }
            })
            .catch(err => {
                console.error("applepay.config error", err);
            });

        function onApplePayClicked() {
            // Create server order first
            fetch('/api/token-payments', { method: 'POST' })
                .then(r => r.json())
                .then(order => {
                    const orderId = order.id;
                    // Initialize PayPal Apple Pay flow
                    // Use PayPal's applepay component to create an ApplePay session, validate merchant, and confirm order
                    applepay.createSession({
                        total: {
                            label: "Demo Purchase",
                            amount: order.purchase_units[0].amount.value,
                            currency: order.purchase_units[0].amount.currency_code
                        },
                        onvalidatemerchant: function (validationURL) {
                            // Use PayPal SDK helper - PayPal provides .validateMerchant for you
                            return applepay.validateMerchant({validationURL});
                        },
                        onpaymentauthorized: function (payment) {
                            // When Apple Pay authorizes, confirm order with PayPal
                            // The PayPal applepay component will call confirmOrder which returns the order id, etc.
                            return applepay.confirmOrder({orderID: orderId})
                                .then(function(confirmResp){
                                    // After confirmOrder, you still need to capture on your server (Orders V2 capture)
                                    return fetch('/api/token-payments/' + orderId + '/capture', { method: 'POST' })
                                        .then(r => r.json());
                                });
                        }
                    }).then(function (session) {
                        // session started and Apple Pay sheet shown
                    }).catch(function (err) {
                        console.error('Error creating Apple Pay session', err);
                    });
                });
        }
    })();
</script>
</body>
</html>
